<template>
	<div>
		<SearchForm
			@reset="reset"
			@search="search"
			ref="search"
			:form="queryParams">
			<FormItem
				v-for="item in SearchFormItems"
				:FormItem="item"
				@FormItem="val => (item = val)"
				v-model="queryParams"></FormItem>
		</SearchForm>
		<div class="tablePage">
			<div class="card-wrap card-padding">
				<div class="table-title-wrap justify-end">
					<el-button
						type="primary"
						icon="el-icon-plus"
						@click="
							_toPage({
								path: '/finance/addReimburs',
								name: 'AddReimburs',
							})
						"
						size="mini"
						v-hasPermi="['finance:reimburs:list:add']">
						新增
					</el-button>
					<el-button
						type="primary"
						@click="putin"
						size="mini"
						v-hasPermi="['finance:reimburs:list:putup']">
						提报
					</el-button>
					<el-button
						type=""
						icon="el-icon-upload2"
						size="mini"
						@click="exportFile"
						v-hasPermi="['finance:reimburs:list:export']">
						导出
					</el-button>
				</div>
				<table-page
					ref="table"
					v-loading="loading"
					:dataList="datalist"
					:total="total"
					:page.sync="queryParams.pageNum"
					:limit.sync="queryParams.pageSize"
					:border="true"
					:isSelect="true"
					@setSizeCurrent="getList"
					@selectionChange="selectionChange">
					<!-- 操作插槽 -->
					<template slot="tableColAc">
						<el-table-column
							align="center"
							label="操作"
							width="150">
							<template slot-scope="scope">
								<div>
									<el-button
										type="text"
										@click="
											_toPage({
												path: '/finance/previewReimburs',
												name: 'PreviewReimburs',
												query: {
													id: scope.row.id,
													type: 'preview',
													processId: scope.row.flowId,
												},
											})
										"
										v-hasPermi="[
											'finance:reimburs:list:look',
										]">
										查看
									</el-button>
									<el-button
										v-if="scope.row.editFlag == 1"
										v-hasPermi="[
											'finance:reimburs:list:edit',
										]"
										type="text"
										@click="
											_toPage({
												path: '/finance/editReimburs',
												name: 'EditReimburs',
												query: {
													id: scope.row.id,
												},
											})
										">
										编辑
									</el-button>
									<!-- <el-button -->
									<!-- type="text" -->
									<!-- @click=" -->
									<!-- _toPage({ -->
									<!-- path: '/finance/previewReimburs', -->
									<!-- query: { -->
									<!-- id: scope.row.id, -->
									<!-- type: 'audit', -->
									<!-- }, -->
									<!-- }) -->
									<!-- "> -->
									<!-- 审核 -->
									<!-- </el-button> -->
								</div>
							</template>
						</el-table-column>
						<el-table-column
							v-for="item in tableItem"
							:label="item.label"
							align="center"
							:min-width="item.minWidth"
							:show-overflow-tooltip="item.showOverflowTooltip">
							<template slot-scope="scope">
								<template v-if="item.type == 'btn'">
									<el-link
										v-if="notEmpty(scope.row.businessCode)"
										type="primary"
										@click="toDetails(scope.row)">
										{{ scope.row[item.prop] }}
									</el-link>
									<span v-else>-</span>
								</template>
								<template
									v-if="
										!item.filterable && item.type !== 'btn'
									">
									{{ scope.row[item.prop] || '-' }}
								</template>
								<template
									v-if="
										item.filterable && item.type !== 'btn'
									">
									{{ item.filter(scope.row) }}
								</template>
							</template>
						</el-table-column>
					</template>
				</table-page>
			</div>
		</div>
	</div>
</template>
<script>
	import Cookies from 'js-cookie';
	import * as apis from '@/api/finance/reimburs/list/api.js';
	import FormItem from '../formItem/index.vue';
	export default {
		name: 'Reimburs',
		components: { FormItem },
		dicts: ['expense_business_type'],
		mixins: [],
		props: {},
		data() {
			return {
				loading: false,
				// SearchFormItems: [],
				tableItem: [],
				queryParams: {
					pageNum: 1,
					pageSize: 10,
					costTypes: '',
				},
				datalist: [],
				total: 0,
				dicts: {
					// 合同类型
					contractType: [
						{
							label: '短租',
							value: '1',
						},
						{
							label: '渠道',
							value: '2',
						},
						{
							label: '自营',
							value: '3',
						},
						{
							label: '代收代付',
							value: '4',
						},
					],
					// 提报类型
					applyType: [
						{
							label: '手动提报',
							value: '0',
						},
						{
							label: '自动生成',
							value: '1',
						},
					],
					costTypes: [],
					costTypesLoading: false,
				},
				selected: [],
			};
		},
		computed: {
			userId() {
				return Cookies.get('userId');
			},
			SearchFormItems() {
				return [
					{
						label: '报销类型:',
						type: 'select',
						prop: 'businessType',
						selectList: this.dict.type.expense_business_type,
						// prototype: {
						//     multiple: true,
						//     collapseTags: true,
						// },
						event: {
							type: 'change',
							cb: row => {
								if (this.notEmpty(row.businessType)) {
									this.getDict(row.businessType);
								}
								row.costTypes = '';
							},
						},
					},
					{
						label: '费用类型:',
						type: 'select',
						prop: 'costTypes',
						selectList: this.dicts.costTypes,
						selectLabel: 'dictLabel',
						selectValue: 'dictValue',
						prototype: {
							loading: this.dicts.costTypesLoading,
						},
					},
					{
						label: '合同类型:',
						type: 'select',
						prop: 'contractType',
						prototype: {
							multiple: true,
							collapseTags: true,
						},
						selectList: this.dicts.contractType,
					},
					{
						label: '报销编号:',
						type: 'input',
						prop: 'businessId',
					},

					{
						label: '业务编号:',
						type: 'input',
						prop: 'businessCode',
					},
					{
						label: '申请人:',
						type: 'input',
						prop: 'applyUserName',
					},
					{
						label: '提报类型:',
						type: 'select',
						prop: 'applyType',
						selectList: this.dicts.applyType,
					},
				];
			},
		},
		watch: {},
		mounted() {
			this.init();
		},
		activated() {
			this.getList();
		},
		methods: {
			async getDict(businessType) {
				try {
					let dictList = [];
					this.dicts.costTypesLoading = true;
					switch (businessType) {
						case '1':
							dictList = await this._getDicts(
								'expense_business_cleancar',
							);
							break;
						case '2':
							dictList = await this._getDicts(
								'expense_business_fuel',
							);
							break;
						case '3':
							dictList = await this._getDicts(
								'expense_business_stopcar',
							);
							break;
						case '4':
							dictList = await this._getDicts(
								'expense_business_road',
							);
							break;
						case '5':
							dictList = await this._getDicts(
								'expense_business_car',
							);
							break;
						case '6':
							dictList = await this._getDicts(
								'expense_business_pay',
							);
							break;
						case '7':
							dictList = await this._getDicts(
								'expense_business_transport',
							);
							break;
						case '8':
							dictList = await this._getDicts(
								'expense_business_registration',
							);
							break;
						case '9':
							dictList = await this._getDicts(
								'expense_business_inspect',
							);
							break;
						case '10':
							dictList = await this._getDicts(
								'expense_business_gps',
							);
							break;
						case '11':
							dictList = [];
							break;
						case '12':
							dictList = await this._getDicts(
								'expense_business_other',
							);
							break;
					}
					this.dicts.costTypesLoading = false;
					this.dicts.costTypes = dictList;
				} catch (error) {
					this.dicts.costTypesLoading = false;
				}
			},
			exportFile() {
				let params = this._.cloneDeep(this.queryParams);
				delete params.pageNum;
				delete params.pageSize;
				params.contractType = params.contractType?.join('|');
				this.download(
					'/expense/main/moreSheetExport',
					params,
					`费用报销列表_${new Date().getTime()}.xlsx`,
				);
			},
			putin() {
				// if (this.selected?.length > 1) {
				// 	this.$message({
				// 		type: 'warning',
				// 		message: '只能选择一条记录',
				// 	});
				// 	return;
				// }
				if (this.selected?.length == 0) {
					this.$message({
						message: '请先勾选一条数据',
						type: 'warning',
					});
					return;
				}
				if (this.selected[0]?.editFlag !== 1) {
					this.$message({
						message: '此项已经提报',
						type: 'error',
					});
					return;
				}
				let ids = this.selected.reduce((prev, next) => {
					return `${prev}${prev ? ',' : ''}${next.id}`;
				}, '');

				let params = {
					id: ids,
					userId: this.userId,
				};
				this.$confirm('此操作将提报此流程, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
				})
					.then(() => {
						this.loading = true;
						apis?.Putin(params)
							.then(res => {
								if (res.code == 200) {
									this.$message.success('提报成功');
									this.selected = [];
									this.$refs.table?.table_clearSelection();
									this.getList();
								}
							})
							.finally(() => {
								this.loading = false;
							});
					})
					.catch(() => {});
			},
			selectionChange(val) {
				this.selected = val;
			},
			init() {
				this.initTable();
				this.getList();
			},

			initTable() {
				this.tableItem = [
					{
						label: '所属公司',
						prop: 'companyName',
						type: 'text',
						showOverflowTooltip: true,
					},
					{
						label: '月份',
						prop: 'payTime',
						type: 'text',
						showOverflowTooltip: true,
					},
					{
						label: '报销类型',
						prop: 'businessTypes',
						type: 'text',
						filterable: true,
						minWidth: '150px',
						filter: val => {
							let result = [];
							this.dict.type.expense_business_type?.map(item => {
								if (
									val.businessTypes?.includes(item.value * 1)
								) {
									result.push(item.label);
								}
							});
							return result && result?.join('/');
						},
						showOverflowTooltip: true,
					},
					{
						label: '费用类型',
						prop: 'costTypeNames',
						type: 'text',
						minWidth: '150px',
						showOverflowTooltip: true,
					},
					{
						label: '费用合计',
						filterable: true,
						filter: row => {
							return this.format_thousand(row.costMoney);
						},
						showOverflowTooltip: true,
					},
					{
						label: '报销编号',
						prop: 'businessId',
						type: 'text',
						minWidth: '250px',
					},
					{
						label: '业务编号',
						prop: 'businessCode',
						type: 'btn',
						minWidth: '250px',
					},
					{
						label: '报销状态',
						prop: 'expenseStatus',
						type: 'text',
						showOverflowTooltip: true,
					},
					{
						label: '合同类型',
						prop: 'contractType',
						type: 'text',
						filterable: true,
						showOverflowTooltip: true,
						filter: val => {
							let val_raw = val.contractType?.split(',');

							let result = [],
								word = '';
							let el = this.dicts.contractType.map(item => {
								if (val_raw?.includes(item.value)) {
									result.push(item.label);
								}
							});
							word = result?.join('/') ?? '-';
							return word;
						},
					},
					{
						label: '生成方式',
						showOverflowTooltip: true,
						filterable: true,
						filter: row => {
							let item = this.dicts.applyType.find(
								item => item.value == row.applyType,
							);
							return item.label ?? '-';
						},
					},
					{
						label: '申请人',
						prop: 'applyUserName',
						type: 'text',
						showOverflowTooltip: true,
					},
					{
						label: '申请人组织',
						prop: 'applyDeptName',
						type: 'text',
						showOverflowTooltip: true,
						minWidth: '100px',
					},
					{
						label: '申请时间',
						prop: 'createTimeStr',
						type: 'text',
						showOverflowTooltip: true,
					},
					{
						label: '收款人类型',
						prop: 'payeeType',
						type: 'text',
						minWidth: '100px',
						showOverflowTooltip: true,
						filterable: true,
						filter: row => {
							let payeeTypeList = [
								{
									label: '员工',
									value: '1',
								},
								{
									label: '司机',
									value: '2',
								},
								{
									label: '供应商',
									value: '3',
								},
							];
							let item = payeeTypeList.find(
								item => item.value == row.payeeType,
							);
							return item?.label ?? '-';
						},
					},
					{
						label: '收款人姓名',
						prop: 'payeeUserName',
						type: 'text',
						minWidth: '100px',
						showOverflowTooltip: true,
					},
				];
			},
			getParams(businessCode) {
				return new Promise((resolve, reject) => {
					this.$modal.loading('正在跳转中，请稍后...');
					apis.Params(businessCode)
						.then(res => {
							if (res.code == 200) {
								if (this.notEmpty(res.data)) {
									resolve(res.data);
								} else {
									throw new Error(res.msg);
								}
							} else {
								throw new Error(res.msg);
							}
						})
						.catch(err => {
							reject(err);
						})
						.finally(() => {
							this.$modal.closeLoading();
						});
				});
			},
			async toDetails(row) {
				let route = {};
				if (/^PCH.*/g.test(row.businessCode)) {
					route = {
						path: '/workflow/examine/details',
						name: 'Details',
						query: {
							processId: row.businessFlowId,
							flag: '1',
							status: 'readonly',
						},
					};
				}
				try {
					let { businessDataId, carId, id, flowId, workOrderType } =
						await this.getParams(row.businessCode);
					// 上牌
					if (/^SP.*/g.test(row.businessCode)) {
						route = {
							path: '/cwgd/registrationDetails',
							name: 'RegistrationDetails',
							query: {
								type: 'view',
								businessDataId: businessDataId,
								carId: carId,
								id: id,
							},
						};
					}
					// 购置税
					if (/^GZS.*/g.test(row.businessCode)) {
						route = {
							path: '/cwgd/purchaseTaxDetails',
							name: 'PurchaseTaxDetails',
							query: {
								type: 'view',
								businessDataId: businessDataId,
								flowId: flowId || null,
							},
						};
					}
					// 年检
					if (/^NJ.*/g.test(row.businessCode)) {
						route = {
							path: '/cwgd/inspectDetails',
							name: 'InspectDetails',
							query: {
								id: id,
								carId: carId,
								businessDataId: businessDataId,
								types: 'view',
								flowId: flowId || null,
							},
						};
					}

					// 装饰
					if (/^ZS.*/g.test(row.businessCode)) {
						route = {
							path: '/cwgd/decorationDetails',
							name: 'DecorationDetails',
							query: {
								types: 'view',
								businessDataId: businessDataId,
								carId: carId,
								workOrderId: id,
								flowId: flowId || null,
							},
						};
					}
					// 维修
					if (/^WX.*/g.test(row.businessCode)) {
						route = {
							path: '/cwgd/maintenanceDetails',
							name: 'MaintenanceDetails',
							query: {
								types: 'view',
								businessDataId: businessDataId,
								carId: carId,
								id: id,
								flowId: flowId || null,
							},
						};
					}
					// 更换轮胎
					if (/^GHLT.*/g.test(row.businessCode)) {
						route = {
							path: '/cwgd/replaceTireDetails',
							name: 'ReplaceTireDetails',
							query: {
								type: 'view',
								businessDataId: businessDataId,
								carId: carId,
								id: id,
								flowId: flowId || null,
							},
						};
					}
					// 保养
					if (/^BY.*/g.test(row.businessCode)) {
						route = {
							path: '/cwgd/maintainDetails',
							name: 'MaintainDetails',
							query: {
								type: 'view',
								businessDataId: businessDataId,
								carId: carId,
								flowId: flowId || null,
								id: id,
							},
						};
					}
					// GPS
					if (/^GPS.*/g.test(row.businessCode)) {
						console.log('GPS');
						if (workOrderType == 12) {
							// this.$router.push({
							route = {
								name: 'GPSInstall',
								query: {
									// data: [row],
									carIds: carId,
									workOrderType: workOrderType,
									type: 'disabled',
									pageType: 'GPS安装工单详情',
								},
							};
						} else if (workOrderType == 13) {
							// this.$router.push({
							route = {
								name: 'GPSRenewal',
								query: {
									// data: row,
									carIds: carId,
									workOrderType: workOrderType,
									type: 'disabled',
									pageType: 'GPS续费工单详情',
								},
							};
						} else if (workOrderType == 14) {
							// this.$router.push({
							route = {
								name: 'GPSFix',
								query: {
									// data: row,
									carIds: carId,
									workOrderType: workOrderType,
									type: 'disabled',
									pageType: 'GPS维修工单详情',
								},
							};
						} else if (workOrderType == 15) {
							// this.$router.push({
							route = {
								name: 'GPSRemove',
								query: {
									// data: row,
									carIds: carId,
									workOrderType: workOrderType,
									type: 'disabled',
									pageType: 'GPS拆除工单详情',
								},
							};
						} else if (workOrderType == 17) {
							// this.$router.push({
							route = {
								name: 'GPSCheck',
								query: {
									// data: row,
									carIds: carId,
									workOrderType: workOrderType,
									type: 'disabled',
									pageType: 'GPS排查工单详情',
								},
							};
						}
					}
				} catch (error) {
					console.error(error);
					this.$message.error('未查找到相关订单信息！');
				}
				console.log(route);
				if (this.notEmpty(route)) {
					this._toPage(route);
				}
			},

			getList() {
				this.loading = true;
				let params = this._.cloneDeep(this.queryParams);
				// params.businessType= params.businessType?.join(",");
				params.contractType = params.contractType?.join('|');
				apis.List(params)
					.then(res => {
						if (res.code == 200) {
							this.datalist = res.rows ?? [];
							this.total = res.total ?? 0;
						}
					})
					.finally(() => {
						this.loading = false;
					});
			},
			reset() {
				this.$refs.search.resetFields();
				this.queryParams = { pageNum: 1, pageSize: 10 };
				this.getList();
			},
			search() {
				this.queryParams.pageNum = 1;
				this.getList();
			},
		},
	};
</script>
<style lang="scss" scoped>
	::v-deep .el-button {
		span {
			user-select: auto;
		}
	}
</style>
